import React, { Component } from 'react';
import { Button, Drawer, Alert, Divider, Badge, Modal, Upload, Icon } from 'antd';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, TableCustomize, openSuccessModal, openModalMessage } from '../../../components/TableCustomize';
import { baseUrl, toLead } from '../../../config';
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import * as APIService from '../../../axios/api_yq'
import { Link } from 'react-router-dom';
import { withPermission } from '../../../components/withpermission'
const CreateButton = withPermission(Button, 'plus')
const DeleteButton = withPermission(Button, 'line')
const DownLoadButton = withPermission(Button, 'download')
const UploadButton = withPermission(Button, 'upload')
const { confirm } = Modal;
export default class ClassMaintain extends Component {
    state = {
        dataSource: [
        ],
        inquire: [],
        paging: {},
        visible: false,
        formData: {},
        drawerVisible: false,
        drawerTitle: '',
        createTime: null,
        one: false,
        loading: false,
        some: null,
        selectedRows: [],
        advanced: false,
        values: {},
        selectedRowKeys: [],
        CalssData: null,
        control: false,
        buttonList: [],
        buttonLoading: false
    };
    // 挂载前
    UNSAFE_componentWillMount() {
        this.fetch();
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化加载数据
    fetch = (page = 1, size = 100) => {
        const { values } = this.state
        const buttonList = JSON.parse(localStorage.getItem('buttonList'))
        console.log('这是按钮', buttonList);
        if (buttonList ? buttonList.length !== 0 : null) {
            this.setState({
                buttonList
            })
        }
        this.setState({
            loading: true,
            one: false,
            drawerVisible: false,
            formData: {},
            some: null,
            paging: { pageNum: page, pageSize: size }
        })
        let a = { pageNum: page, pageSize: size }
        setTimeout(() => {
            this.search({ ...values, ...a })
        }, 300);
    }
    // 查询接口
    search = (value, paging) => {
        APIService.queryGroup(value, paging).then((item) => {
            console.log(item);
            if (item.data.code === 200) {
                this.setState({
                    loading: false,
                    dataSource: item.data.data.data,
                    // 操作后清除选中
                    selectedRowKeys: [],
                    selectedRows: [],
                    some: null,
                    paging: {
                        pageNum: item.data.data.pageNum,
                        pageSize: item.data.data.pageSize,
                        total: item.data.data.total,
                    }
                })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 新增、编辑接口
    newOrCompile = (value) => {
        const { values, paging } = this.state
        APIService.alterGroup(value).then((item) => {
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.search({ ...values, ...paging })
                this.handleCancel()
            } else {
                this.setState({
                    buttonLoading: false
                })
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 成员管理
    deleteRow = (data) => {
        console.log('发送数据', data);
        sessionStorage.setItem('members', JSON.stringify(data))
    }
    // 当前行获得数据
    deleteRow1 = (b) => {
        APIService.addGroup().then((value) => {
            let data = value.data.data
            this.setState({
                one: true,
                drawerVisible: true,
                formData: b,
                drawerTitle: '编辑',
                CalssData: data
            });
        })
    }
    // 停用
    stop = (c) => {
        let a = { ...c, isDelete: 1 }
        this.newOrCompile(a)
    }
    // 启用
    startUsing = (c) => {
        let a = { ...c, isDelete: 0 }
        this.newOrCompile(a)
    }
    // 删除
    deleteRow2 = (data) => {
        const then = this
        // console.log('删除', data);
        const { values, paging } = this.state
        let id = `idList=${[data.id]}`
        console.log(id);
        confirm({
            title: '确认删除当前班组吗，这将影响其他使用班组数据的模块?',
            onOk() {
                APIService.deleteGroup(id).then((item) => {
                    if (item.data.code === 200) {
                        then.search({ ...values, ...paging })
                        openSuccessModal(item.data.msg)
                    } else {
                        openModalMessage('error', item.data.msg)
                    }
                })
            },
            onCancel() {
            },
        })
    }
    // 新增数据/修改
    onHandleOk = () => {
        const { formData } = this.state
        this.formDrawer.validateFields((err, value) => {
            if (err) return;
            let amend = { ...value, id: formData.id, groupLeaderId: this.state.userIds }
            console.log('数据', amend);
            this.setState({
                buttonLoading: true
            }, () => {
                this.newOrCompile(amend)
            })

        })
    }
    // 取消
    handleCancel = e => {            //表单重置函数
        this.formAdd && this.formAdd.resetFields();
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            visible: false,
            drawerVisible: false,
            one: false,
            formData: {},
            buttonLoading: false
        });
    };
    // 根据条件查询
    handleSearch = value => {
        const { paging } = this.state
        let a = { pageNum: paging.pageNum, pageSize: paging.pageSize }
        this.setState({
            values: value
        })
        console.log('条件查询数据', { ...value, ...a });
        this.search({ ...value, ...a })
    };
    //0新增
    create = () => {
        APIService.addGroup().then((value) => {
            console.log(value);
            let data = value.data.data
            this.setState({
                one: false,
                drawerVisible: true,
                drawerTitle: '新增',
                CalssData: data
            });
        })
    };
    // 导出模板
    derive = () => {
        APIService.exportExcelDemo12().then(res => {
            console.log(res);
            //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
            let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
            // 创建A标签
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // 设置的下载文件文件名
            const fileName = decodeURI('班组维护');
            // 触发点击方法
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
        })
    }
    // 导出选中
    derive1 = () => {
        const { selectedRows } = this.state
        // 拿到的数据
        let selectedRowss = [...selectedRows]
        let a = [
            ...selectedRowss
        ]
        console.log(a);
        if (this.state.some !== null && this.state.some > 0) {
            APIService.exportExcel12(a).then(res => {
                //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
                let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
                // 创建A标签
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                // 设置的下载文件文件名
                const fileName = decodeURI('班组维护');
                // 触发点击方法
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
            })
        } else {
            openModalMessage('error', '请选中导出项')
        }
    }

    // 重置
    cz = () => {
        const { paging } = this.state
        this.setState({
            values: null
        }, () => { this.fetch() })

    }
    // 高级查询
    advancedss = () => {
        console.log('高级查询');
        this.setState({ advanced: !this.state.advanced })
    }
    // 按钮点击事件
    // btnClick = (a) => {
    //     if (a === 0) {
    //         this.create()
    //     }
    //     if (a === 1) {
    //         this.derive()
    //     }
    //     if (a === 2) {
    //         this.derive1()
    //     }
    // }
    render() {
        const then = this
        const { buttonLoading, buttonList, control, CalssData, selectedRowKeys, advanced, some, one, paging, loading, dataSource, formData, drawerVisible, drawerTitle } = this.state;
        const rowSelection = {
            columnWidth: 60,
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                let some = [...selectedRows].length
                this.setState({
                    some: some,
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                }, () => {
                    console.log('选中个数', this.state.some, '选中详细数据', this.state.selectedRows);
                })
                if (some === 0 || some === null) {
                    this.setState({
                        control: false
                    })
                } else {
                    this.setState({
                        control: true
                    })
                }
            },
            // 固定在左侧
            // fixed: true
        }
        const columns = [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '班组编码',
                dataIndex: 'groupCode',
                width: 100,
            },
            {
                title: '集团',
                width: 100,
                dataIndex: 'company',
            },
            {
                title: '工厂',
                width: 130,
                dataIndex: 'factory',
            },
            {
                title: '班组名称',
                width: 130,
                dataIndex: 'groupName',
            },
            {
                title: '所属车间',
                width: 150,
                dataIndex: 'workShop',
            },
            {
                title: '默认机位',
                width: 200,
                dataIndex: 'seat',
            },
            {
                title: '班组长',
                width: 100,
                dataIndex: 'groupLeader',
            },
            {
                title: '成员数',
                width: 80,
                dataIndex: 'members',
            },
            {
                title: '班组类型',
                width: 100,
                dataIndex: 'groupType',
            },
            {
                title: '状态',
                dataIndex: 'isDelete',
                width: 100,
                render: (text, record) =>
                    record.isDelete === 1 ? <Badge status="error" text={'停用'} /> : <Badge status='success' text={'启用'} />
            },
            {
                title: '操作',
                dataIndex: 'opts',
                width: 220,
                render:
                    (text, record) =>
                        <div>
                            <Link to='/member' onClick={this.deleteRow.bind(this, record)}>{'成员管理'}</Link>
                            <Divider type="vertical" />
                            <a onClick={this.deleteRow1.bind(this, record)}>{'编辑'}</a>
                            <Divider type="vertical" />
                            {
                                record.isDelete === 1 ? <a onClick={this.startUsing.bind(null, record)} >{'启用'}</a> : <a onClick={this.stop.bind(null, record)} >{'停用'}</a>
                            }
                            <Divider type="vertical" />
                            <a onClick={this.deleteRow2.bind(null, record)}>{'删除'}</a>
                        </div>
            },
            { dataIndex: '' }
        ]
        // 导入
        const propss = {
            name: 'file',
            action: `${baseUrl}${toLead}/groupManage/importExcel`,
            accept: '.xls,.xlsx',
            method: 'post',
            showUploadList: true,
            headers: {
                userId: localStorage.getItem('userId'),
                Token: localStorage.getItem('token'),
            },
            onChange(info) {
                console.log('这是', info);
                if (info.file.status !== 'uploading') {
                    console.log('这是什么', info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    openSuccessModal('导入成功')
                    then.fetch()
                } else if (info.file.status === 'error') {
                    openModalMessage('error', '错误')
                }
            },
        }
        return <div>
            <BasicLayoutSearch>
                <SearchForm onSearch={this.handleSearch}
                    onClick={this.cz}
                    onClick1={this.advancedss}
                    advanced={advanced}
                />
            </BasicLayoutSearch>
            {
                control === true ? <Alert message={<div>已选择 <span style={{ color: '#5abcff' }}>{some}</span> 项 </div>} type="info" showIcon style={{ width: '99%', margin: 'auto' }} /> : null
            }

            <BasicLayout
                name="生产班组维护"
                icon="table"
                buttons={[
                    <CreateButton key={1} onClick={this.create} icon='plus' />,
                    <DownLoadButton key={3} onClick={this.derive} icon='download' text="导出模板" />,
                    <DownLoadButton key={4} onClick={this.derive1} icon='download' text="导出选中" />,
                    <Upload {...propss} key={6}>
                        <UploadButton icon='upload' />
                    </Upload>,

                    // <Button key={1} onClick={this.create} type="primary" icon='plus'>新增</Button>,
                    // <Button key={4} onClick={this.derive} type="primary" icon='download'>导出模板</Button>,
                    // <Button key={5} onClick={this.derive1} type="primary" icon='download'>导出选中</Button>,
                    // <Upload {...propss} key={6}>
                    //     <Button type="primary">
                    //         <Icon type="upload" /> 导入
                    //     </Button>
                    // </Upload>,
                ]}
            >
                <TableCustomize
                    rowSelection={rowSelection}
                    columns={columns}
                    rowKey={(record) => record.id}
                    dataSource={dataSource}
                    pagination={false}
                    loading={loading}
                    allowDrafting={true}
                    scroll={{ x: true, y: 600 }}
                    rowClassName={(record, index) => {
                        return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                    }}
                />
                <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
            </BasicLayout>
            <Drawer width={500} visible={drawerVisible} title={drawerTitle} onClose={this.handleCancel} destroyOnClose>
                <AddForm
                    formData={formData}
                    one={one}
                    onOk={this.onHandleOk}
                    ref={node => (this.formDrawer = node)}
                    onClose={this.handleCancel}
                    CalssData={CalssData}
                    userIds={(v) => { this.setState({ userIds: v }) }}
                />
                <div
                    style={{
                        position: 'absolute',
                        right: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                    <Button type="primary" onClick={this.onHandleOk} loading={buttonLoading}>
                        {'确认'}
                    </Button>
                </div>
            </Drawer>
        </div>;
    }
}
